<?php

/**
 +------------------------------------------------------------
 * 公用控制器
 +------------------------------------------------------------
 * @author	liuricheng
 * @time	2014-03-13
 * @type	[mod]
 * 
 */

import("ORG.Util.Function"); 
import("ORG.Util.RBAC");// 权限类
import("@.Org.SystemTool");
import("@.Org.PowerTool");


class PublicAction extends Action{
	
	/**
	 * 所有的空操作都指向login
	 * Enter description here ...
	 * 
	 */
	public function _empty(){
		$this->login();		
	}
	
	/**
	 * 登陆
	 * 
	 */
	function login(){
		$this->display();
	}	
	
	/**
	 * 刷新页面-验证登陆
	 * @param	name
	 * @param	password
	 * 
	 */
	function checkLogin1(){
		
		$userName		=	$this->_post('name');
		$password		=	$this->_post('password');
		$msg			=	array(  );		
		$map            =   array();	/* 验证条件 */
		
		// 检查格式: 用户名,邮箱,手机
		if(empty($userName)) {
			$this->returnData("用户名不能为空");
		}elseif (empty($password)){
			$this->returnData("密码不能为空");
		}
				
		// 支持使用绑定帐号登录
		$map['name']		= 	$userName;			
		$authInfo 			= 	RBAC::authenticate($map);
			
		//使用用户名、密码和状态的方式进行认证
		if(false === $authInfo) {
			$this->returnData("帐号不存在");
		}else{
			if($authInfo['password'] != md5($_POST['password'])) {
				$this->returnData("密码与用户名不匹配");
			}
			$_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
			//if user is admin,start the adminstrator
			if($authInfo['name']=='admin') {
				$_SESSION['administrator']		=	true;
			}
			//session记录登陆的用户信息
			$Users                    =     new Model('User');
			$con                      =     "name='" . $map['name']."'";
			$userInfo                 =     $Users->field("id,name")->where($con)->find();
			$_SESSION['name']         =     $userInfo['name'];
			$_SESSION['user_name']    =     $userInfo['name'];//兼容前台用户
			$_SESSION['id']           =     $userInfo['id'];
			$_SESSION['user_id']      =     $userInfo['id'];//兼容前台用户系统
				
			// 缓存访问权限
			RBAC::saveAccessList();
			//t(RBAC::getAccessList($authInfo['id']));
			$msg	=	array(
				'num'=>1,
				'msg'=>'登录成功',
				'url'=>U("Index/index")
			);
			$this->returnData($msg);
		}
				
	}
	
	/**
	 * 验证登陆
	 * Enter description here ...
	 */
	public function checkLogin(){
		$CommonModel	=	new CommonModel();
		
	    if (!empty($_SESSION['captcha_word']) && (intval($GLOBALS['_CFG']['captcha']) & CAPTCHA_ADMIN)){	
	        /* 检查验证码是否正确
	        $validator = new captcha();
	        if (!empty($_POST['captcha']) && !$validator->check_word($_POST['captcha'])){
	            sys_msg($_LANG['captcha_error'], 1);
	        }
	        */
	    }
	
	    $_POST['username'] 			= 	isset($_POST['username']) ? trim($_POST['username']) : '';
	    $_POST['password'] 			= 	isset($_POST['password']) ? trim($_POST['password']) : '';
	
	    $sql						=	" SELECT `ec_salt` FROM " . 'ybr_admin_user' ." WHERE user_name = '" . $_POST['username']."'";	    	    
	    $ec_salt 					=	$CommonModel->getOne($sql);

	    /* 检查密码是否正确 */
	    if(!empty($ec_salt)){	         
	         $sql 					= 	"SELECT user_id, user_name, password, last_login, action_list, last_login,suppliers_id,ec_salt".
							            " FROM " . 'ybr_admin_user' .
							            " WHERE user_name = '" . $_POST['username']. "' AND password = '" . md5(md5($_POST['password']).$ec_salt) . "'";
	    }
	    else{
	         /* 检查密码是否正确 */
	         $sql 					= 	"SELECT user_id, user_name, password, last_login, action_list, last_login,suppliers_id,ec_salt".
							            " FROM " . 'ybr_admin_user' .
							            " WHERE user_name = '" . $_POST['username']. "' AND password = '" . md5($_POST['password']) . "'";
	    }

	    $row 						= 	$CommonModel->getRow($sql);
	    
	    
	    if ($row){
	        // 检查是否为供货商的管理员 所属供货商是否有效
	        if (!empty($row['suppliers_id'])){
	            $supplier_is_check 	= 	suppliers_list_info(' is_check = 1 AND suppliers_id = ' . $row['suppliers_id']);
	            
	            if (empty($supplier_is_check)){
	                $this->error($GLOBALS['_LANG']['login_disable']);
	            }
	        }
	
	        // 登录成功
	        set_admin_session($row['user_id'], $row['user_name'], $row['action_list'], $row['last_login']);
	        
	        // 后台管理人员权限获取
	        // 支持使用绑定帐号登录
			$map['user_name']				= 	$_POST['username'];				
			$authInfo 						= 	RBAC::authenticate($map);
			
			$_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
			//if user is admin,start the adminstrator
			if($authInfo['user_name']=='admin') {
				$_SESSION['administrator']	=	true;
			}
			//session记录登陆的用户信息
			
			$_SESSION['name']         		=     $authInfo['user_name'];
			$_SESSION['user_name']    		=     $authInfo['user_name'];	//兼容前台用户
			$_SESSION['id']           		=     $authInfo['user_id'];
			$_SESSION['user_id']      		=     $authInfo['user_id'];	//兼容前台用户系统
				
			// 缓存访问权限
			RBAC::saveAccessList($authInfo['user_id']);
	        
	        $_SESSION['suppliers_id'] 		= 	$row['suppliers_id'];
	        
			if(empty($row['ec_salt'])){
				$ec_salt		=	rand(1,9999);
				$new_possword	=	md5(md5($_POST['password']).$ec_salt);
	            $CommonModel->query("UPDATE " .'ybr_admin_user'.
	                 " SET ec_salt='" . $ec_salt . "', password='" .$new_possword . "'".
	                 " WHERE user_id='$_SESSION[admin_id]'");
			}
	
	        if($row['action_list'] == 'all' && empty($row['last_login'])){
	            $_SESSION['shop_guide'] = true;
	        }
	
	        // 更新最后登录时间和IP
	        $CommonModel->query("UPDATE " .'ybr_admin_user' .
	                 " SET last_login='" . gmtime() . "', last_ip='" . real_ip() . "'".
	                 " WHERE user_id='$_SESSION[admin_id]'");
	
	        if (isset($_POST['remember'])){
	            $time 			=	gmtime() + 3600 * 24 * 365;
	            setcookie('ECSCP[admin_id]',   $row['user_id'],                            $time);
	            setcookie('ECSCP[admin_pass]', md5($row['password'] . $GLOBALS['_CFG']['hash_code']), $time);
	        }
	
	        //清除购物车中过期的数据
	        clear_cart();
	        	        
	        $url	=	'<meta http-equiv="refresh" content="2; url=' . U('index/index') . '" />';
	        $this->assign("tips_text" , 	"登陆成功,正在为您跳转.....");
	        $this->assign("tips_url",		$url);
	        $this->display('msg');
	    }
	    else{
	        $url	=	'<meta http-equiv="refresh" content="2; url=' . U('public/login') . '" />';
	        $this->assign("tips_text" , 	"登陆失败,正在为您跳转.....");
	        $this->assign("tips_url",		$url);
	        $this->display('msg');
	    }
	}
	
	/**
	 * 返回数据
	 * @param	msg
	 * 
	 */
	public function returnData($var){
		
		$datas		=	array(
			'num'=>0,	
			'msg'=>'',
			'url'=>'' //跳转页面路径
		);
		
		// 判断提交过来的数据类型
		if(is_string($var)){
			$datas['msg']	=	$var;
		}
		else if(is_numeric($var)){
			$datas['num']	=	$var;
		}
		else if(is_array($var)){
			$datas			=	array_merge($datas,$var);
		}
		
		if($this->isAjax()){
			$this->ajaxReturn($datas);
		}
		else{
			empty($datas['url']) ? $this->success($datas['msg']) : $this->success($datas['msg'],$datas['url']);
		}
	}
	
	/**
	 * 退出系统
	 * 
	 */
	function loginout(){
		if(isset($_SESSION[C('USER_AUTH_KEY')])){
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
        }else {
        	session_destroy();
        }   
        $url	=	'<meta http-equiv="refresh" content="2; url=' . U('public/login') . '" />';
        $this->assign("tips_text" , 	"成功退出系统,正在为您跳转.....");
        $this->assign("tips_url",		$url);
        $this->display();
	}
	
		
}

